<template>
    <a-modal :keyboard="false" :maskClosable="false" title="表扬工单管理" :open="visible" :width="900" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <!-- <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单类型" v-bind="validateInfos.orderType">
                        <a-radio-group v-model:value="modelRef.orderType" @change="handleOrderTypeChage">
                            <a-radio v-for="(value, key) in typeMap" :key="key" :value="Number(key)">{{ value }}工单</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col> -->
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单来源" v-bind="validateInfos.orderSource">
                        <a-radio-group v-model:value="modelRef.orderSource">
                            <a-radio v-for="item in sourceData" :value="item.value" :key="item.value">{{ item.label }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单属性" v-bind="validateInfos.orderProperty">
                        <a-select v-model:value="modelRef.orderProperty">
                            <a-select-option v-for="(value, key) in propertyMap" :key="key" :value="Number(key)">{{ value }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="项目名称" v-bind="validateInfos.projectCode">
                        <a-cascader
                            v-model:value="modelRef.projectCode"
                            :options="treeData"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'code',
                            }"
                            placeholder="选择项目名称"
                            style="width: 100%"
                            @change="handleCascaderChange"
                        />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6" v-if="modelRef.projectCode">
                    <a-form-item label="房间号" v-bind="validateInfos.propertyId">
                        <a-cascader
                            v-model:value="modelRef.propertyId"
                            :options="buildData"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'id',
                            }"
                            placeholder="选择房间号"
                            style="width: 100%"
                            @change="handleBuildChange"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="业主姓名" v-bind="validateInfos.propertyOwnerId">
                        <a-input v-model:value="modelRef.propertyOwner" disabled />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="业主电话" v-bind="validateInfos.propertyPhone">
                        <a-input v-model:value="modelRef.propertyPhone" disabled />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="联系人" v-bind="validateInfos.contactPerson">
                        <a-input v-model:value="modelRef.contactPerson" />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="联系人电话" v-bind="validateInfos.contactPersonPhone">
                        <a-input v-model:value="modelRef.contactPersonPhone" />
                    </a-form-item>
                </a-col>
                <!-- <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单分类" v-bind="validateInfos.orderTypeSub">
                        <a-select
                            v-model:value="modelRef.orderTypeSub"
                            style="width: 100%"
                            :options="[
                                {
                                    label: '户内',
                                    value: 0,
                                },
                                {
                                    label: '公区',
                                    value: 1,
                                },
                            ]"
                            @change="handleOrderTypeSubChange"
                        ></a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item :label="'详细分类'" v-bind="validateInfos.orderClassifyId">
                        <a-select
                            v-model:value="modelRef.orderClassifyId"
                            style="width: 100%"
                            :disabled="!!modelRef.orderSub"
                            :options="createDictData"
                            :field-names="{ value: 'id', label: 'classifyName' }"
                            placeholder="请先选择工单分类"
                            @change="handleClassifyIdChange"
                        ></a-select>
                    </a-form-item>
                </a-col> -->
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="工单描述" v-bind="validateInfos.content">
                        <a-textarea v-model:value="modelRef.content" show-count :maxlength="500"></a-textarea>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="工单附件">
                        <custom-upload v-model:fileList="modelRef.fileList" />
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType, Ref } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { cloneDeep, isEmpty } from 'lodash-es';
    import type { TreeProps } from 'ant-design-vue';
    import { txList } from '@/api/common/proline';
    // import { options, statusMap, propertyMap, typeMap } from './common';
    import { queryProjectTree } from '@/api/list/project-list';
    import { getPropertyBasic } from '@/api/list/property-list';
    import { queryBuildTree2Room } from '@/api/list/build';
    import { getList } from '@/api/order/cate';
    import { createPraise, getPraise } from '@/api/order/praise-list';
    import { dictDataListByDictType } from '@/api/user/dict';
    import { validatePhone } from '@/utils/validate';
    import { options, statusMap, propertyMap, typeMap } from '../mine-list/common';

    const fieldNames: TreeProps['fieldNames'] = {
        children: 'children',
        title: 'name',
        key: 'code',
    };

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const treeData: Ref<TreeProps['treeData']> = ref([]);
            const buildData = ref<any[]>([]);
            const roleList = ref<any[]>([]);
            const sourceData = ref<any[]>([]);
            const createDictData = ref<any[]>([]);
            const defaultForm = {
                status: 1,
                // orderClassifyId: '',
                // orderClassifyName: '',
                // orderTypeSub: '',
                orderSource: '',
                contactPersonPhone: '',
                contactPerson: '',
                projectCode: '',
                orderType: '',
                orderProperty: '',
                content: '',
                fileList: [],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                // orderClassifyId: [{ required: true, message: '请选择详细分类' }],
                // orderType: [{ required: true, message: '请选择工单类型' }],
                orderProperty: [{ required: true, message: '请选择工单属性' }],
                content: [{ required: true, message: '请输入工单描述' }],
                projectCode: [{ required: true, message: '请选择' }],
                contactPerson: [{ required: true, message: '请输入联系人姓名' }],
                contactPersonPhone: [{ required: true, message: '请输入联系人电话' }, { validator: validatePhone }],
                // orderTypeSub: [{ required: true, message: '请选择' }],
                orderSource: [{ required: true, message: '请选择' }],
                // fileList: [{ required: true, message: '请上传' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    txList().then(res => {
                        if (!isEmpty(res.data)) roleList.value = res.data;
                    });

                    dictDataListByDictType({
                        dictType: 'order_ascription',
                    }).then(res => {
                        sourceData.value = res.data;
                    });
                    queryTreeData();

                    if (props.model) {
                        Object.assign(modelRef, props.model, {
                            // orderTypeSub: isEmpty(props.model.orderTypeSub) ? [] : props.model.orderTypeSub.split(','),
                        });
                    }
                }
            });

            const queryBuildTreeData = (codes: any[]) => {
                queryBuildTree2Room(codes[codes.length - 1]).then(build => {
                    buildData.value = isEmpty(build.data) ? [] : build.data;
                    console.log(buildData.value);
                });
            };

            const queryTreeData = () => {
                queryProjectTree().then(res => {
                    treeData.value = [res.data as any];
                });
            };

            const handleCascaderChange = (value: any, selectedOptions: any) => {
                const select = selectedOptions[selectedOptions.length - 1];
                console.log(value, select, modelRef);
                modelRef.projectName = select.name;
                if (select.type === 'dept' && select.children.length === 0) {
                    queryBuildTreeData(value);
                } else {
                    message.warning('当前选择无项目');
                    buildData.value = [];
                }
            };

            const handleBuildChange = (value: any, selectedOptions: any) => {
                const select = selectedOptions[selectedOptions.length - 1];
                console.log(value, select);

                getPropertyBasic(select.id).then(res => {
                    console.log(res);
                    if (!isEmpty(res.data)) {
                        const { owner: propertyOwner, phone: propertyPhone, propertyOwnerId, floorId } = res.data;
                        Object.assign(modelRef, {
                            propertyOwner,
                            propertyOwnerId,
                            propertyPhone,
                            contactPersonPhone: propertyPhone,
                            contactPerson: propertyOwner,
                            floorId,
                        });
                    }
                });
            };

            const handleOrderTypeSubChange = val => {
                console.log(val);
                getList({
                    orderTypeSub: val,
                    orderType: modelRef.orderType,
                    status: 1,
                }).then(res => {
                    console.log(res);
                    createDictData.value = res.data;
                });
            };

            const handleClassifyIdChange = (val, options) => {
                console.log(val, options);
                modelRef.orderProfessionalLine = options.orderProfessionalLine;
                modelRef.orderClassifyName = options.classifyName;
            };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                console.log(modelRef);

                validate()
                    .then(res => {
                        console.log(res);
                        loading.value = true;

                        createPraise({
                            ...(modelRef as any),
                            projectCode: modelRef.projectCode[modelRef.projectCode.length - 1],
                            propertyId: modelRef.propertyId[modelRef.propertyId.length - 1],
                            orderType: 2,
                        })
                            .then(res => {
                                if (res.data) {
                                    message.success('操作成功');
                                    emit('success');
                                    handleCancel();
                                }
                            })
                            .finally(() => {
                                loading.value = false;
                            });
                    })
                    .catch(err => {
                        console.log(err);
                    });
            };

            const handleOrderTypeChage = () => {
                modelRef.orderTypeSub = '';
                modelRef.orderClassifyId = '';
            };
            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                fieldNames,
                options,
                statusMap,
                propertyMap,
                typeMap,
                roleList,
                sourceData,
                createDictData,
                isEmpty,

                treeData,
                buildData,
                handleCascaderChange,
                handleBuildChange,
                handleOrderTypeSubChange,
                handleClassifyIdChange,
                handleOrderTypeChage,
            };
        },
        components: {},
    });
</script>
